<?php

/**
 * SECURE URL
 *
 * Esta clase dibuja los links solo si tenes permisos para accederlos
 *
 * TODO: Usar decorators para dibujar el link.
 */
class Ext_View_Helper_Surl extends Zend_View_Helper_Abstract
{

    private $_user = null;

   /**
     * Generates an url given the name of a route.
     *
     * @access public
     *
     * @param  string $controller
     * @param  string $action
     * @param  string $desc description
     * @param  string $args array of arguments
     * @return string Url for the link href attribute.
     */
    public function surl( $controller = null, $action = null, $args = array(), $extraFmt =  "%s", $module = null, $reset = true )
    {
    	if ( is_string( $args ) && $module ===  null ) {
    		$module = $args;
    		$args = array();
    	}
        if ( $controller === null ) {
            $controller = Zend_Controller_Front::getInstance()->getRequest()->getControllerName();
        }
        if ( $action === null ) {
            $action = Zend_Controller_Front::getInstance()->getRequest()->getActionName();
        }

    	if ( empty( $module ) ) {
            $module = Zend_Controller_Front::getInstance()->getRequest()->getModuleName();
        }
        
        if ( empty( $this->_user ) ) {
            $auth = Zend_Auth::getInstance();
            if ( $auth->hasIdentity() ) {
                // Identity exists; get it
                $this->_user = $auth->getIdentity();
            }
        }
        $applicationId = null;
        if ( !is_null( $module ) && $module != Zend_Controller_Front::getInstance()->getDefaultModule() ) {
    		$applicationId = $this->view->GetApplicationId( $module );
        }
		if ( ! empty( $this->_user ) && $this->_user->isAllowed( $controller, $action, $applicationId ) ) {
			$args['controller'] = $controller;
			$args['action'] = $action;
			$args['module'] = $module;
			$ret = $this->view->url( $args, null, $reset );
            return sprintf( $extraFmt, $ret );
        }
        error_log( "Este modulo no tiene permisos");
        error_log( print_r(array( $controller, $action, $applicationId ),true));
        return "";
    }
}
